package com.spark.common.ext

import android.annotation.SuppressLint
import android.app.Activity
import android.app.ActivityManager
import android.app.Application
import android.content.ActivityNotFoundException
import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.support.annotation.IntRange
import android.support.v4.app.Fragment
import android.support.v4.provider.DocumentFile
import android.support.v7.widget.GridLayoutManager
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.UnderlineSpan
import android.util.TypedValue
import android.view.Window
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.Toast
import com.blankj.utilcode.util.LogUtils
import java.io.File
import java.io.FileOutputStream
import java.text.SimpleDateFormat
import java.util.*

/**
 * Context toast
 */
fun Context.toast(message: CharSequence) = Toast.makeText(this, message, Toast.LENGTH_SHORT).show()

/**
 * Fragment toast
 */
fun Fragment.toast(message: CharSequence) = Toast.makeText(activity, message, Toast.LENGTH_SHORT).show()

/**
 * Fragment toast
 */
fun android.app.Fragment.toast(message: CharSequence) = Toast.makeText(activity, message, Toast.LENGTH_SHORT).show()

/**
 * window 设置背景透明度
 */
fun Window.windowOpacity(@IntRange(from = 0, to = 1) alpha: Float) {
    val lp = attributes
    lp.alpha = alpha
    addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
    attributes = lp
}

/**
 * Activity 设置被禁透明度
 */
fun Activity.windowOpacity(alpha: Float) {
    val lp = window.attributes
    lp.alpha = alpha
    window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
    window.attributes = lp
}


/**
 * 判断 Activity 是否存活
 */
fun Activity?.isAlive(): Boolean {
    if (this == null) return false
    if (!this.isDestroyed && !this.isFinishing) {
        return true
    }
    return false
}

/**
 * 获取应用名称
 */
fun Application.getAppNanme(): String? {
    val am = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
    val myPid = android.os.Process.myPid()
    am.runningAppProcesses.forEach {
        if (myPid == it.pid) {
            return it.processName
        }
    }
    return ""
}

/**
 * 获取输入法管理器
 */
fun Context.imm(): InputMethodManager {
    return getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
}

/**
 * dp2px
 */
fun Context?.dp2px(dp: Float): Float {
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, this?.resources?.displayMetrics)
            ?: 0F
}


/**
 * px2dp
 */
fun Context.px2dp(px: Float): Float {
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, px, resources.displayMetrics)
}

fun Activity.px2dp(px: Float): Float {
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, px, resources.displayMetrics)
}

fun Context.sp2px(sp: Float): Float {
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, resources.displayMetrics)
}

fun Activity.sp2px(sp: Float): Float {
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, resources.displayMetrics)
}

fun Context.px2sp(px: Float): Float {
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, px, resources.displayMetrics)
}

fun Activity.px2sp(px: Float): Float {
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, px, resources.displayMetrics)
}

/**
 * SimpleDateFormat
 * yyy-MM-dd HH:mm:ss
 */
fun <T> T.sdf(format: String = "yyyy-MM-dd"): SimpleDateFormat {
    return SimpleDateFormat(format, Locale.getDefault())
}

/**
 * 隐藏输入法显示
 */
fun Activity.hideIm() {
    val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(window.decorView.windowToken, 0)
}

/**
 * TextView 的 String 设置颜色
 */
fun String.color(beforeColor: Int, afterColor: Int, divider: Int): SpannableStringBuilder {
    val beforeColorSpan = ForegroundColorSpan(beforeColor)
    val afterColorSpan = ForegroundColorSpan(afterColor)
    val ssb = SpannableStringBuilder(this)
    ssb.setSpan(beforeColorSpan, 0, divider, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
    ssb.setSpan(afterColorSpan, divider, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
    return ssb
}

/**
 * TextView 的 String 设置下划线
 */
fun String.underline(start: Int, end: Int): SpannableStringBuilder {
    val underlineSpan = UnderlineSpan()
    val ssb = SpannableStringBuilder(this)
    ssb.setSpan(underlineSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
    return ssb
}

/**
 * TextView 的 String 设置颜色、下划线
 */
fun String.colorWithUnderline(beforeColor: Int, afterColor: Int, start: Int, end: Int): SpannableStringBuilder {
    val beforeColorSpan = ForegroundColorSpan(beforeColor)
    val afterColorSpan = ForegroundColorSpan(afterColor)
    val underlineSpan = UnderlineSpan()

    val ssb = SpannableStringBuilder(this)

    ssb.setSpan(beforeColorSpan, 0, start, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
    ssb.setSpan(afterColorSpan, start, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
    ssb.setSpan(underlineSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
    return ssb
}

fun String.colorWithUnderline(color: Int): SpannableStringBuilder {
    val colorSpan = ForegroundColorSpan(color)
    val underlineSpan = UnderlineSpan()
    val ssb = SpannableStringBuilder(this)
    ssb.setSpan(color, 0, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
    ssb.setSpan(underlineSpan, 0, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
    return ssb

}


fun Window.setBackgroundAlpha(@IntRange(from = 0, to = 1) alpha: Float) {
    val lp = attributes
    lp.alpha = alpha
    addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
    attributes = lp
}

/**
 * 获取本地文件路径（不包含文件名及后缀名）
 */
fun <T> T.getFilePathWithoutName(path: String): String {
    val filePath = File(path).absolutePath
    val lastSplash = filePath.lastIndexOf("/")
    return filePath.substring(0, lastSplash)
}

fun <T> T.getFileNameWithoutPostfix(path: String): String {
    val filePath = File(path).absolutePath
    val lastSplash = filePath.lastIndexOf("/")
    val lastDot = filePath.lastIndexOf(".")
    var fileName = filePath.substring(lastSplash, lastDot)
    if (fileName.isNullOrBlank()) {
        fileName = SimpleDateFormat("yyyy-MM-ss-HHmmss", Locale.getDefault()).format(Date())
    }
    return fileName
}


fun Activity.realPath(resId: Int): String {
    return Uri.parse(
            "${ContentResolver.SCHEME_ANDROID_RESOURCE}://" +
                    "${resources.getResourcePackageName(resId)}/" +
                    "${resources.getResourceTypeName(resId)}/" +
                    resources.getResourceEntryName(resId)).toString()
}

fun Bitmap.file(destFile: File) {
    if (destFile.exists())
        destFile.delete()
    var fos: FileOutputStream? = null
    try {
        fos = FileOutputStream(destFile)
        compress(Bitmap.CompressFormat.PNG, 100, fos)
    } catch (e: Exception) {
        e.printStackTrace()
    } finally {
        fos?.apply {
            flush()
            close()
        }
    }
}

fun EditText.string(): String {
    return text.toString().trim()
}

/**
 * 监听 EditText 的focus 变化，改变 text 内容和 cursor 位置
 */
@SuppressLint("SetTextI18n")
fun EditText.trackPostfix(postfix: String) {
    setOnFocusChangeListener { v, hasFocus ->
        val value = string()
        if (hasFocus) {
            if (!value.isNullOrBlank() && value.contains(postfix)) {
                setText(value.substring(0, value.length - 1))
                setSelection(string().length)
            }
        } else {
            if (!value.isNullOrBlank()) setText("$value$postfix")
        }
    }
}

fun Activity.singleFileChooser(resultCode: Int) {
    val intent = Intent(Intent.ACTION_GET_CONTENT).apply {
        type = "*/*"
        addCategory(Intent.CATEGORY_OPENABLE)
    }
    try {
        startActivityForResult(Intent.createChooser(intent, "上传文件"), resultCode)
    } catch (e: ActivityNotFoundException) {
        e.printStackTrace()
        LogUtils.e("请安装文件管理器")
        toast("请安装文件管理器")
    }
}

/**
 * 选择多个文件
 */
fun Activity.mutliFile(requestCode: Int) {
    val intent = Intent().apply {
        action = Intent.ACTION_GET_CONTENT
        type = "*/*"
        addCategory(Intent.CATEGORY_OPENABLE)
        putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
    }
    startActivityForResult(Intent.createChooser(intent, "PickFile"), requestCode)
}

/**
 * 选择单个文件
 */
fun Activity.singleFile(requestCode: Int) {
    val intent = Intent().apply {
        action = Intent.ACTION_GET_CONTENT
        type = "*/*"
        addCategory(Intent.CATEGORY_OPENABLE)
        putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
    }
    startActivityForResult(Intent.createChooser(intent, "PickFile"), requestCode)
}

/**
 * @param requestCode 请求码[返回]
 * @param resultCode 结果码[返回]
 * @param originRequestCode 原请求码
 * @param intent
 */
fun Activity.onChooseFileResult(requestCode: Int, resultCode: Int, originRequestCode: Int, intent: Intent?) {
    if (requestCode == originRequestCode && resultCode == Activity.RESULT_OK) {
        intent?.apply {
            val docFile: DocumentFile = DocumentFile.fromSingleUri(this@onChooseFileResult, data)
            LogUtils.e("【ChooseFile】【filename】${docFile.name} 【filetype】${docFile.type} 【uri】${docFile.uri}")
            // RxFile.createFileFromUri(this@onChooseFileResult,docFile.uri).subscribe { LogUtils.e(it) }
        }
    }
}

fun Context.glm(count: Int, reverse: Boolean = false, orientation: Int = GridLayoutManager.VERTICAL, vscroll: Boolean = false, hscroll: Boolean = false): GridLayoutManager {
    return object : GridLayoutManager(this, count, orientation, reverse) {
        override fun canScrollVertically(): Boolean {
            return vscroll
        }

        override fun canScrollHorizontally(): Boolean {
            return hscroll
        }

        override fun isAutoMeasureEnabled(): Boolean {
            return true
        }
    }
}